<template>
  <div class="pg-login-page">

    <div class="pg-navbar">
      <div class="pg-nav-item pl-20">
        <div class="pg-nav-logo d-flex align-items-center">
          <img src="@/assets/logo.svg" width="28" height="28" />
          <span class="brand">蒲公英</span>
        </div>
      </div>
    </div>

    <div class="body">
      <div class="form-container">
        <div :class="`bg-${type}`" @click="toggleLoginType" v-if="step === 0"></div>
        <h3 class="login-title">{{ step === 0 ? (type === 'qrcode' ? '微信扫码登录' : '蒲公英运营中心') : (type === 'qrcode' ?
          '关联已有账号' : '微信授权') }}</h3>
        <div class="qrcode-container" v-if="type==='qrcode' && step === 0 || type === 'password' && step === 1">
          <iframe frameborder="0" scrolling="no" :src="qrconnect_url">
          </iframe>
          <div class="expiration-mask" v-if="isExpiration">二维码已过期</div>
          <div class="tips">
            使用微信扫一扫{{ type==='qrcode' && step === 0 ? '登录' : '授权' }}
            <a class="ml-5" @click="signQrconnectUrl">刷新</a>&nbsp;
            <i class="icon-sync" :class="`${refreshing ? 'spinner' : ''}`"></i>
          </div>
        </div>
        <pg-form
            class="mt-30"
            size="lg"
            item-width="100%"
            v-if="(type==='password' && step === 0) || (type === 'qrcode' && step === 1)"
            ref="loginForm"
        >
          <pg-form-item label="用户名" :show-label="false" :rules="{ 'required': logic_required }">
            <pg-input
                ref="login-name"
                placeholder="请输入登录手机"
                v-model="loginData.login_name"
                material
                auto-focus
                @keyup.enter.native="handleLogin"
            >
              <span slot="prefix" class="pl-5">
                <i class="icon-mobile"></i>
              </span>
            </pg-input>
          </pg-form-item>
          <pg-form-item label="密码" :show-label="false" :rules="{ 'required': logic_required }">
            <pg-input
                material
                type="password"
                ref="login-password"
                placeholder="请输入登录密码"
                v-model="loginData.password"
                @keyup.enter.native="handleLogin"
            >
              <span slot="prefix" class="pl-5">
                <i class="icon-lock2"></i>
              </span>
            </pg-input>
          </pg-form-item>
          <pg-form-item class="mt-20">
            <pg-button size="lg" style="height: 40px;" color="primary" block @click="handleLogin" id="btn-submit" :loading="loading">登录</pg-button>
          </pg-form-item>
        </pg-form>

        <div class="browser-desc">推荐使用 谷歌浏览器 和 火狐浏览器</div>

      </div>

    </div>

    <div class="pg-footer">
      <div class="copyright">
        Copyright &copy; {{ year }} pgyscm.com All Rights Reserved. 深圳蒲公英农业科技有限公司 版权所有
      </div>
    </div>
  </div>
</template>

<script>

  import md5 from 'md5';
  import {Http, Config} from '@/util';

  export default {
    name: "login",
    inject: ['app'],
    computed: {
      year() {
        return new Date().getFullYear();
      }
    },
    created() {
      document.title = '用户登录 - 蒲公英运营管理中心';
      this.$data.type === 'qrcode' && this.signQrconnectUrl();

      // 在登录页面 判断子系统跳转该页面传递的参数，向app 注册参数。
      const {href, origin, client} = this.$route.query;
      !this.app.isPro && console.log('【$route query】:', this.$route.query);
      this.app.$data.oauth_href = href ? decodeURIComponent(href) : '';
      this.app.$data.oauth_origin = origin ? decodeURIComponent(origin) : '';
      this.app.$data.oauth_client = client ? decodeURIComponent(client) : '';

      this.logic_required = {
        validate: (v) => {
          return !!(v + '').trim();
        },
        getMsg: ' ',
      }
    },
    beforeDestroy() {
      this.interval && clearInterval(this.interval);
    },
    data() {
      return {
        type: 'qrcode', //  qrcode | password
        step: 0,

        refreshing: false, // 刷新二维码
        loading: false, // 提交loading
        isExpiration: false,

        login_key: '',
        qrconnect_url: '',

        loginData: {
          login_name: '',
          password: '',
        },

        wechatInfo: {
          snsapi_openid: '',
          wechat_unionid: '',
        },

      }
    },
    methods: {
      /**
       * 账号密码 + 扫码:
       *  /m/sign/login 返回的login_key、qrconnect_url
       *  轮询: /sign/login/confirm 参数login_key
       *
       * 直接扫码:
       *  /m/sign/qrconnect/url
       *  轮询: /sign/login/confirm 参数login_key
       *
       * 登陆失败账号绑定:
       *  /sign/wechat/bind  参数: login_name、password、snsapi_openid、wechat_unionid
       */
      intervalConfirm() {
        this.interval = setInterval(() => {
          Http.post(Config.api.signLoginConfirm, {login_key: this.$data.login_key}, {throttle: false, handleError: false})
            .then(res => {

              if (res.code === 0) { // 表示绑定成功 或者 登录成功
                this.interval && clearInterval(this.interval);
                let rd = res.data || {};
                if (!rd.jwt_token) {
                  this.$toast({ type: 'danger', message: '用户登录异常' });
                  return;
                }
                this.app?.handleLogin(res.data);
                return;
              }

              if (res.code === 2) { // 表示需要绑定账号密码
                this.interval && clearInterval(this.interval);
                this.$data.wechatInfo = res.data;
                this.$data.step = 1;
                return;
              }

              if (res.code === 9) { // 表示二维码已过期
                this.interval && clearInterval(this.interval);
                this.$data.isExpiration = true;
                return;
              }

              if (res.code === 1) { // 登录报错
                this.interval && clearInterval(this.interval);
                this.$toast({ type: 'danger', message: res.message });
                return;
              }

            });
        }, 2000);
      },

      toggleLoginType() {
        this.interval && clearInterval(this.interval);
        if (this.$data.type === 'qrcode') {
          this.$data.type = 'password';
        } else if (this.$data.type === 'password') {
          this.$data.type = 'qrcode';
          this.signQrconnectUrl();
        }
        this.$data.step = 0;
      },

      // 如果是切换到了 qrcode 登录，则自动刷新URL
      async signQrconnectUrl() {

        this.$data.login_key = '';
        this.$data.qrconnect_url = '';
        this.interval && clearInterval(this.interval); // 请求二维码时，首先重置url 和 计时器

        if (this.$data.refreshing) return;

        this.$data.refreshing = true;
        let res = await Http.get(Config.api.signQrconnectUrl);
        this.$data.refreshing = false;

        if (res.code !== 0) return;
        this.$data.isExpiration = false; // 二维码请求成功后，设定过期状态为false
        const {login_key, qrconnect_url} = res.data;
        if (!login_key || !qrconnect_url) return;
        this.intervalConfirm(); // 二维码请求成功后，开始计时器
        this.$data.login_key = login_key;
        this.$data.qrconnect_url = qrconnect_url;
      },

      handleLogin() {
        this.$refs['loginForm'].validateAll().then(async (valid) => {

          if (!valid) return;

          // 用户输入合法校验通过。
          if (this.$data.type === 'qrcode' && this.$data.step === 1) { // 表示当前是绑定微信操作
            let formData = {...this.$data.loginData, ...this.$data.wechatInfo};
            formData.password = md5(formData.password);

            try {
              this.$data.loading = true;
              let res = await Http.post(Config.api.signWechatBind, formData);
              this.$data.loading = false;

              if (res.code === 0) {
                let rd = res.data || {};
                if (!rd.jwt_token) {
                  this.$toast({ type: 'danger', message: '用户登录异常' });
                  return;
                }
                this.app?.handleLogin(res.data);
              } else {
                this.$toast({type: 'danger', message: res.message});
              }
            } catch (e) {
              this.$data.loading = false;
            }
          }

          if (this.$data.type === 'password' && this.$data.step === 0) { // 表示当前是用户输入用户名和密码登录
            let formData = {...this.$data.loginData};
            formData.password = md5(formData.password);
            try {
              this.$data.loading = true;
              let res = await Http.post(Config.api.signLogin, formData, {throttle: false, handleError: false});
              this.$data.loading = false;

              // 暂时禁止 用户扫码确认。

              if (res.code === 0) {
                this.$data.login_key = res.data.login_key;
                this.$data.qrconnect_url = res.data.qrconnect_url;
                this.$data.step = 1;
                this.intervalConfirm();

              } else if (res.code === 6) { // 如果不需要扫码的处理
                let rd = res.data || {};
                if (!rd.jwt_token) {
                  this.$toast({ type: 'danger', message: '用户登录异常' });
                  return;
                }
                this.app?.handleLogin(res.data);

              } else {
                this.$toast({type: 'danger', message: res.message});
              }
            } catch (e) {
              this.$data.loading = false;
            }

          }

        });
      },
    }
  }
</script>

<style lang="scss" scoped>
  .pg-login-page {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
    overflow: hidden;
    background: url("") no-repeat center;
    background-size: cover;
  }

  .pg-login-page .body {
    width: 724px;
    height: 424px;
    position: absolute;
    top: 50%;
    margin-top: -200px;
    left: 50%;
    margin-left: -362px;
    background: url("") no-repeat left center;
    background-size: contain;
    z-index: 10;
    background-color: #076DFF;
    box-shadow: 0 6px 23px 0 rgba(0,0,0,0.08), 0 2px 4px 0 rgba(0,0,0,0.08);
  }

  .body .form-container {
    display: block;
    margin-left: auto;
    width: 362px;
    height: 424px;
    background: #FFFFFF;
    box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.08);
    position: relative;
    padding-top: 65px;
    box-sizing: border-box;
    overflow: hidden;
  }

  .body .form-container .login-title {
    padding: 0 60px;
    text-align: center;
    font-weight: 600;
    font-size: 28px;
    line-height: 40px;
    color: #333;
    user-select: none;
  }

  .body .form-container .pg-form {
    padding: 0 60px;
  }

  .body .form-container .bg-password,
  .body .form-container .bg-qrcode {
    position: absolute;
    right: 0;
    top: 0;
    width: 80px;
    height: 80px;
    background-size: cover;
    cursor: pointer;
  }

  .body .form-container .bg-password {
    background: url("") no-repeat center center;
    transition: all .3s ease-in-out;

    &:hover {
      background-image: url("");
    }

    &::after {
      display: inline-block;
      content: '扫码登录';
      text-align: center;
      font-size: 12px;
      color: #BBBBBB;
      width: 68px;
      height: 20px;
      line-height: 20px;
      background: url("") no-repeat center center;
      background-size: cover;

      position: absolute;
      top: 20px;
      right: 70px;
    }
  }

  .body .form-container .bg-qrcode {
    background: url("") no-repeat center center;
    transition: all .3s ease-in-out;

    &:hover {
      background-image: url("");
    }

    &::after {
      display: inline-block;
      content: '账号登录';
      text-align: center;
      font-size: 12px;
      color: #BBBBBB;
      width: 68px;
      height: 20px;
      line-height: 20px;
      background: url("") no-repeat center center;
      background-size: cover;

      position: absolute;
      top: 20px;
      right: 70px;
    }
  }

  .body .form-container .browser-desc {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 40px;
    /*opacity: 0.4;*/
    background: #FFFFFF;
    background-image: linear-gradient(90deg, rgba(41,118,250,0.10) 0%, rgba(67,38,213,0.10) 100%);

    text-align: center;
    font-size: 12px;
    line-height: 40px;
    color: #076DFF;
  }

  .body .qrcode-container {
    margin-top: 10px;
    width: 100%;
    height: 340px;
    overflow: hidden;
    text-align: center;
    position: relative;

    iframe {
      width: 100%;
      height: 100%;
      transform: scale(.7);
      margin-top: -76px;
    }

    .expiration-mask {
      position: absolute;
      z-index: 100;
      width: 212px;
      height: 212px;
      line-height: 212px;
      top: 0px;
      left: 50%;
      margin-left: -106px;
      text-align: center;
      font-size: 14px;
      color: #5A5D64;
      font-weight: 600;
      background-color: rgba(255, 255, 255, 0.9);
    }
  }

  .body .qrcode-container .tips {
    position: absolute;
    top: 220px;
    width: 100%;
    font-size: 12px;
    color: #666666;

    a {
      user-select: none;
      color: #666666;
      text-decoration: underline;
      cursor: pointer;
    }
  }

  .pg-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 50px;

    .copyright {
      line-height: 50px;
      color: #989797;
      font-size: 12px;
      text-align: center;
    }
  }


</style>